import os
import re
import requests as req

def dfs(directory='.\\HELP\\NOTE_JVM'):
    # 将当前目录下的所有md文件路径添加到tmp.txt列表中
    stack = [directory]

    with open(os.path.join(os.path.dirname(__file__), 'tmp.txt'), 'w', encoding='utf-8') as f:
        while stack:
            current_dir = stack.pop()
            try:
                for entry in os.listdir(current_dir):
                    full_path = os.path.join(current_dir, entry)
                    if os.path.isdir(full_path):
                        stack.append(full_path)
                    elif entry.endswith('.md'):
                        f.write(full_path + '\n')
            except PermissionError:
                print(f"Permission denied: {current_dir}")
                continue

def change_lnk_type(md_path, img_path):
    # 修改md文件中的图片的网络链接为本地路径
    img_url_pattern = re.compile(r'!\[.*?\]\((https?:\/\/[^\s"\'()]+?\.(?:jpg|jpeg|png|gif|bmp)(?:\?[^\s"]*)?)\)')

    with open(md_path, 'r', encoding='utf-8') as fil:
        content = fil.read().strip()

    matches = img_url_pattern.findall(content)
    for match in matches:
    # 下载图片
        try:
            response = req.get(match)
            response.raise_for_status()
            # 提取文件名
            file_name = os.path.basename(match)
            local_path = os.path.join(img_path, file_name)
            with open(local_path, 'wb') as img_file:
                img_file.write(response.content)

            # 替换链接
            local_url = f"![{file_name}]({local_path})"
            content = content.replace(match, local_url)
            print(f"Downloaded and replaced image URL: {match} with {local_url}")
        except Exception as e:
            print(f"Failed to download image {match}: {e}")

    with open(md_path, 'w', encoding='utf-8') as fil:
        fil.write(content)

if __name__ == '__main__':
    directory_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..', 'HELP', 'NOTE_JVM'))
    dfs(directory_path)
    img_path=f'.\\..\\HELP\\img'
    with open('.\\tmp.txt', 'r', encoding='utf-8') as f:
        while 1:
            md_path=f.readline().strip()
            change_lnk_type(md_path,img_path)